package org.JQbitorrentClinet.utils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.JQbitorrentClinet.QBitorrentConnectionInfo;
import org.JQbitorrentClinet.base.BaseParam;
import org.JQbitorrentClinet.utils.InternalHttpClient;
import org.JQbitorrentClinet.utils.Utils;
import org.apache.http.client.methods.CloseableHttpResponse;

import java.util.Map;

@Slf4j
public class RequestHandler {

    @SneakyThrows
    public static <T> T handleRequest(BaseParam param, QBitorrentConnectionInfo connectionInfo) {

        Map paramMap = param.getParamMap();
        CloseableHttpResponse response = null;
        InternalHttpClient internalHttpClient = connectionInfo.getInternalHttpClient();

        log.info("RequestHandler: handleRequest:{},type:{}", connectionInfo.getUrl(param), param.getRequestType());
        //HTTP请求
        switch (param.getRequestType()){
            case GET:
                response =  internalHttpClient.get(connectionInfo.getUrl(param));
                break;
            case GETURLENCODED:
                response = internalHttpClient.get(connectionInfo.getUrl(param), paramMap);
                break;
            case POST:
                response = internalHttpClient.post(connectionInfo.getUrl(param));
                break;
            case POSTURLENCODED:
                response =  internalHttpClient.postBodyParm(connectionInfo.getUrl(param), paramMap);
                break;
            case POSTMULTIPART:
                response = internalHttpClient.postMultiPart(connectionInfo.getUrl(param), paramMap);
                break;
            case DELETE:
                response = internalHttpClient.deleteBodyParam(connectionInfo.getUrl(param), paramMap);
                break;
        }

        Utils.responseCheck(response);
        T content = Utils.convertEntity(response,param.getResponseType());

        return content;
    }
}
